package domain.command;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.dsrg.soenea.domain.MapperException;
import org.dsrg.soenea.domain.command.CommandError;
import org.dsrg.soenea.domain.command.CommandException;
import org.dsrg.soenea.domain.command.impl.Command;
import org.dsrg.soenea.domain.helper.Helper;
import org.dsrg.soenea.domain.mapper.DomainObjectNotFoundException;
import org.dsrg.soenea.uow.MissingMappingException;
import org.dsrg.soenea.uow.UoW;

import domain.model.group.Group;
import domain.model.group.GroupProxy;
import domain.model.group.IGroup;
import domain.model.group.mapper.GroupInputMapper;
import domain.model.group.mapper.GroupOutputMapper;
import domain.model.user.User;
import domain.model.user.mapper.UserInputMapper;

public class RemoveMemberCommand extends Command{

	private boolean post;

	public RemoveMemberCommand(Helper helper, boolean ispost) {
		super(helper);
		post = ispost;
	}

	public void setUp() throws CommandException {
	}


	public void process() throws CommandException {

		User remover = null;
		long uid = -1, gid = -1;
		List<User> userList = null;
		List<User> memberList = new ArrayList<User>();

		try
		{

			//First getting the user and group info 
			uid = (Long)helper.getSessionAttribute("userid");
			remover = UserInputMapper.find(uid);
			gid = remover.getGroup().getId();


			// if "POST" then try to remove user.
			if (post) 
			{
				removeMember();
			}

			//getting all users and count how many in the group
			userList = UserInputMapper.findAll();
			int numOfMembers = 0;

			//adding only the people in the same group to a member list
			for(User u: userList)
			{
				if(u.getGroup().getId() == gid)
				{
					memberList.add(u);
					numOfMembers++;
				}
			}

			if(numOfMembers == 0)
			{
				Group g = GroupInputMapper.find(gid);
				GroupOutputMapper gop = new GroupOutputMapper();
				gop.delete(g);
			}
			
			// set attributes to pass to the view
			helper.setRequestAttribute("groupId", gid);
			helper.setRequestAttribute("memberList", memberList);

		}
		catch (Exception e) 
		{		
			e.printStackTrace();
			throw new CommandException(e.getMessage());			
		}

	}

	public void tearDown() throws CommandError 
	{
		
	}

	//Helping method for doing the actual removal
	private void removeMember() throws SQLException, MissingMappingException, MapperException, InstantiationException, IllegalAccessException
	{
		
		User removedUser = null;
		long removeUserId = -1;
		long removeUserVersion = -1;

		// get the user for removal
		removeUserId = helper.getLong("userId");
		removeUserVersion = helper.getLong("userversionForRemoval");
		removedUser = UserInputMapper.find(removeUserId);
		removedUser.setVersion(removeUserVersion);

		//setting the group to 0   ** Might be a better way to do this...
		IGroup gr = new GroupProxy((long) 0);
		removedUser.setGroup(gr);

		UoW.getCurrent().registerDirty(removedUser);
		UoW.getCurrent().commit();
		
	}


}
